import signService from './service/signService';
import commons from './commons/commons';
import wxRequestService from './service/wxRequestService';

export default class MiniToGameSdk {
    constructor() {
        this.version = '1.0.1' // sdk版本
        this.isInit = false // 是否初始化完成
        this.isDebug = 0 // 是否调试
        this.appid = '' // 小程序appid
        this.wxOpenid = '' // 小程序用户openid
        this.startInfo = {} // 启动完成参数
        this.launchInfo = {} // 冷启动数据
        this.onShowInfo = {} // 热启动数据
        this.serverAppkey = 'a9330f4d727f9751eaea490e9311dda2' // 签名key
        this.serverHost = 'https://mtg-sdk-server.xingyi-games.com' // 请求服务器地址
        this.logHost = 'https://mtg-sdk-server.xingyi-games.com' // 上报日志服务器
    }

    // 是否初始化完成
    checkInit() {
        return this.isInit
    }

    // 是否登录完成
    checkLogin() {
        return this.wxOpenid.length > 1
    }

    // 打印调试信息
    printDebug(...args) {
        if (!this.isDebug == 1) {
            return
        }
        let now = commons.formatDate(new Date(), 'YmdHis.u')
        let params = Array.prototype.slice.call(args);
        console.log('[SDK DEBUG]['+now+']', JSON.stringify(params))
    }

    // callback
    cbRes(func, res) {
        this.printDebug('回调请求结果原样', res)
        func(res)
    }

    // callback true
    cbTrue(func, data = {}) {
        this.printDebug('回调成功结果', data)
        func({
            code: 0,
            msg: 'success',
            data: data
        })
    }

    // callback fail
    cbFail(func, errno, errmsg, data={}) {
        this.printDebug('回调失败结果', errno, errmsg)
        func({
            code: errno,
            msg: errmsg,
            data: data
        })
    }

    // 获得额外参数，用于请求时附带上
    getExtendParams() {
        const _this = this
        let params = {}

        // 基础信息
        params.appid = _this.appid
        params.openid = _this.wxOpenid
        params.sdk_version = _this.version

        // 小程序启动参数
        params.launch_info = JSON.stringify(this.launchInfo)
        params.onshow_info = JSON.stringify(this.onShowInfo)

        return params
    }

    // 上报日志
    addLog(event_id, event_name, params) {
        const _this = this

        // 基础信息
        params.event_id = event_id
        params.event_name = event_name
        params.event_time = Math.floor(Date.now() / 1000)

        // 补充额外数据
        params = Object.assign(_this.getExtendParams(), params)

        // 对数据进行签名
        params.time = Math.floor(Date.now() / 1000)
        let sign_info = signService.createSign(params, this.serverAppkey)
        params.sign = sign_info.sign
        _this.printDebug('签名源串', sign_info.str)

        let url = this.logHost + '/api/mtg/log'

        _this.printDebug('上报日志', url, params)

        return wxRequestService.send(url, params, function(res){})
    }

    send(api, params = {}, cb) {
        const _this = this

        // 补充额外数据
        params = Object.assign(_this.getExtendParams(), params)

        // 对数据进行签名
        params.time = Math.floor(Date.now() / 1000)
        let sign_info = signService.createSign(params, this.serverAppkey)
        params.sign = sign_info.sign
        _this.printDebug('签名源串', sign_info.str)

        let url = this.serverHost + api

        _this.printDebug('发起SDK请求', url, params)

        return wxRequestService.send(url, params, cb)
    }

    // 小游戏冷启动时的参数
    initLaunch() {
        let info = wx.getLaunchOptionsSync()
        this.launchInfo.scene = info.scene
        this.launchInfo.query = info.query
        this.launchInfo.referrerInfo = info.referrerInfo
        this.launchInfo.chatType = info.chatType

        this.printDebug('接收到冷启动参数', info)
        return true
    }

    // 小游戏热启动时的参数
    initOnShow(info) {
        this.onShowInfo.scene = info.scene
        this.onShowInfo.query = info.query

        this.printDebug('接收到热启动参数', info)
        return true
    }

    // 初始化
    init(params = {}, cb) {
        const _this = this
        if (_this.checkInit()) {
            return _this.cbFail(cb, 9999, '无需重复初始化')
        }

        for (const item of ['appid']) {
            if (!params.hasOwnProperty(item)) {
                let msg = '缺少参数: '+item
                return _this.cbFail(cb, 9999, msg)
            }
        }

        _this.appid = params.appid
        _this.isDebug = params.debug || 0

        if (params.hasOwnProperty('server_host')) {
            _this.serverHost = params.server_host
        }
        if (params.hasOwnProperty('log_host')) {
            _this.logHost = params.log_host
        }

        _this.initLaunch()

        _this.isInit = true;
        _this.addLog(1002, 'init', {})

        this.printDebug('初始化成功', params)

        return this.cbTrue(cb, this.launchInfo)
    }

    // 处理登录数据
    handleLogin(data, cb) {
        const _this = this
        _this.wxOpenid = data.openid
        _this.startInfo = Object.assign(data)

        // 先将结果返回，防止等待时间过长
        _this.cbTrue(cb, {
            type: data.type,
            openid: data.openid,
            unionid: data.unionid,
        })

        // 唤起页面
        // https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.redirectTo.html
        if (data.type == 1) {
            if (data.page.type == 'tab') {
                wx.switchTab({
                    url: data.page.path,
                    success(res) {
                        // 打开成功
                        _this.addLog(1003, 'openpage', data)
                    }
                })
            } else {
                wx.redirectTo({
                    url: data.page.path,
                    success(res) {
                        // 打开成功
                        _this.addLog(1003, 'openpage', data)
                    }
                })
            }
            return
        }

        // 唤起H5页面
        // https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.redirectTo.html
        if (data.type == 2) {
            wx.redirectTo({
                url: data.h5.path,
                success(res) {
                    // 打开成功
                    _this.addLog(1003, 'openh5', data)
                }
            })
            return
        }

        // 唤起小程序
        // https://developers.weixin.qq.com/miniprogram/dev/api/navigate/wx.navigateToMiniProgram.html
        if (data.type == 3) {
            wx.redirectTo({
                url: data.mini.path,
                success(res) {
                    // 打开成功
                    _this.addLog(1003, 'openmini', data)
                }
            })
            return
        }
    }

    // 登录
    login(params = {}, cb) {
        const _this = this
        if (!_this.checkInit()) {
            return _this.cbFail(cb, 9999, '初始化未完成')
        }

        wx.login({
            success(res) {
                _this.send('/api/mtg/start/index', {
                    access_token: res.code
                }, res => {
                    if (res.code !== 0) {
                        _this.printDebug('登录失败', res)
                        return _this.cbFail(cb, res.code, res.msg)
                    }
                    _this.handleLogin(res.data, cb)
                    _this.printDebug('登录成功', res)
                })
            },
            fail(e) {
                _this.printDebug('登录失败', e.errCode, e.errMsg)
                return _this.cbFail(cb, e.errCode, e.errMsg)
            }
        })
    }

    getStartInfo(params = {}, cb) {
        const _this = this
        if (!_this.checkLogin()) {
            return _this.cbFail(cb, 9999, '登录未完成')
        }
        _this.cbTrue(cb, _this.startInfo)
    }
}
